package com.yokit.c2c.controller;
import com.yokit.c2c.pojo.User;
import com.yokit.c2c.response.ResponseObject;
import com.yokit.c2c.service.UserService;
import com.yokit.c2c.token.TokenProcessor;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author fengzeng
 * @create 2021/6/13 20:22
 */
@RestController
public class UserController {

  @Resource
  private UserService userService;

  /**
   * 用户登录
   * @param requestBody
   * @return
   */
  @RequestMapping(value = "/login", method = RequestMethod.POST)
  public ResponseObject userLogin(@RequestBody Map<String ,String > requestBody) {
    String username = requestBody.get("username");
    String password = requestBody.get("password");
    if (username == null || password == null) {
      return new ResponseObject(400, "请求参数不合法");
    }
    Optional<User> optionalUser = Optional.ofNullable(userService.selectByUsernameAndPassword(username, password));
    if (optionalUser.isPresent()) {
      User user = optionalUser.get();
      Map data = new HashMap();
      data.put("id", user.getId());
      data.put("userName", user.getUsername());
      data.put("mobile", user.getMobile());
      data.put("isShop", user.getIsShop());
      data.put("token", TokenProcessor.makeToken());
      return new ResponseObject(200, "登录成功", data);
    }
    return new ResponseObject(400, "用户名或密码错误");
  }

  /**
   * 用户注册
   * @param requestBody
   * @return
   */
  @RequestMapping(value = "/registry", method = RequestMethod.POST)
  public ResponseObject UserRegistry(@RequestBody Map<String ,String > requestBody) {
    String username = requestBody.get("username");
    String password = requestBody.get("password");
    String mobile = requestBody.get("mobile");
    if (username == null || password == null || mobile == null) {
      return new ResponseObject(400, "请求参数不合法");
    }
    //创建用户
    User user = new User();
    user.setUsername(username);
    user.setPassword(password);
    user.setMobile(mobile);
    //插入数据库
    userService.createUser(user);

    return new ResponseObject(200, "注册成功");
  }
}
